﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors.Controls;
using System.Collections;
using TERP.Constants;
using TERP.WaterClient.Views;
using TERP.WaterClient.Entities.Auth;
using TERP.WaterClient.Common;
using TERP.WaterClient.DbServices;

namespace TERP.WaterClient.Views.Auth
{
	public partial class FrmMngGroup : FrmMdiBase
	{
		#region Declarations
		private const string CAPTION_INDEX = "STT";
		private const string CAPTION_GRP_CODE = "Mã nhóm";
		private const string CAPTION_GRP_NAME = "Tên nhóm";
		private const string CAPTION_EDIT_STATUS = "Trạng thái";
		//
		private const string CAPTION_USR_CODE = "Mã người dùng";
		private const string CAPTION_USR_NAME = "Tên người dùng";
		private const string CAPTION_DEALER_CODE = "Mã đại lý";
		private const string CAPTION_FLAG_SYS_ADMIN = "Sys Admin";
		//
		private const string CAPTION_IDX = "STT";
		private const string CAPTION_OBJ_CODE = "Mã chức năng";
		private const string CAPTION_OBJ_TYPE = "Loại chức năng";
		private const string CAPTION_PARTNER_CODE = "Loại ứng dụng";
		private const string CAPTION_OBJ_NAME = "Tên chức năng";
		private const string CAPTION_FLAG_ACTIVE = "Kích hoạt";
		//
		private const string FIELD_EDIT_STATUS = "Col_Edit_Status";
		//
		private const string MSG_WARNING_EMPTY_VALUE = "Không được trống";
		private const string MSG_WARNING_DUPLICATE_GRP_CODE = "Mã nhóm đã tồn tại";

		private GroupCollection _grpCollection;
		private Hashtable _htblUsrBelong;
		private Hashtable _htblFunction;
		#endregion

		public FrmMngGroup()
		{
			InitializeComponent();
		}

		private void FrmMngGroup_Load(object sender, EventArgs e)
		{
			InitGrid();
			InitGridItemEditor();
			InitControl();
			SetLanguage();
			this.LoadGroup();
		}

		private void InitControl()
		{
			_htblUsrBelong = new Hashtable();
			_htblFunction = new Hashtable();
		}

		/// <summary>
		/// 
		/// </summary>
		private void SetLanguage()
		{
			this.grpGroup.Text = "Nhóm";
			this.grpProperties.Text = "Thuộc tính";
			this.btnDelete.Text = "Xóa";
			this.btnApply.Text = "Lưu";
			this.btnAdd.Text = "Thêm";
			this.btnClose.Text = "Đóng";
			this.btnReload.Text = "Tải lại";
			this.btnEdit.Text = "Sửa";
			//
			this.tabPageUserBelong.Text = "Người dùng";
			this.tabPageFunctionObj.Text = "Chức năng";
		}

		/// <summary>
		/// 
		/// </summary>
		private void InitGrid()
		{
			SetGridViewStyle(gviewGroup);
			SetGridViewStyle(gviewUserBelong);
			SetGridViewStyle(gviewObjBelong);
			//grid grp
			gridColIdx.Caption = CAPTION_INDEX;
			gridColGrpCode.Caption = CAPTION_GRP_CODE;
			gridColGrpName.Caption = CAPTION_GRP_NAME;
			gridColEditStatus.Caption = CAPTION_EDIT_STATUS;
			//
			gridColIdx.FieldName = TblCommon.Index;
			gridColGrpCode.FieldName = TblGroup.Group_Code;
			gridColGrpName.FieldName = TblGroup.Group_Name;
			gridColEditStatus.FieldName = FIELD_EDIT_STATUS;
			//grid user
			gridColUserIdx.Caption = CAPTION_INDEX;
			gridColUserCode.Caption = CAPTION_USR_CODE;
			gridColUserName.Caption = CAPTION_USR_NAME;
			gridColDealerCode.Caption = CAPTION_DEALER_CODE;
			gridColFlagActive.Caption = CAPTION_FLAG_ACTIVE;
			gridColFlagSysAdmin.Caption = CAPTION_FLAG_SYS_ADMIN;
			//
			gridColUserIdx.FieldName = TblCommon.Index;
			gridColUserCode.FieldName = TblUser.User_Code;
			gridColUserName.FieldName = TblUser.User_Name;
			gridColDealerCode.FieldName = TblUser.Dealer_Code;
			gridColFlagActive.FieldName = TblUser.Flag_Active;
			gridColFlagSysAdmin.FieldName = TblUser.Flag_Sys_Admin;
			//grid function
			this.gridColObjIdx.FieldName = TblCommon.Index;
			this.gridColObjCode.FieldName = TblFunctionObject.Object_Code;
			this.gridColObjType.FieldName = TblFunctionObject.Object_Type;
			this.gridColObjPartnerCode.FieldName = TblFunctionObject.Partner_Code;
			this.gridColObjName.FieldName = TblFunctionObject.Object_Name;
			this.gridColObjFlagActive.FieldName = TblFunctionObject.Flag_Active;
			//
			this.gridColObjIdx.Caption = CAPTION_IDX;
			this.gridColObjCode.Caption = CAPTION_OBJ_CODE;
			this.gridColObjType.Caption = CAPTION_OBJ_TYPE;
			this.gridColObjPartnerCode.Caption = CAPTION_PARTNER_CODE;
			this.gridColObjName.Caption = CAPTION_OBJ_NAME;
			this.gridColObjFlagActive.Caption = CAPTION_FLAG_ACTIVE;
		}

		/// <summary>
		/// 
		/// </summary>
		private void InitGridItemEditor()
		{
			reposImgCmbBox.SmallImages = EmbeddedRes.Instance.ImageListEditStatus;
			reposImgCmbBox.Items.Clear();
			reposImgCmbBox.Items.AddRange(new ImageComboBoxItem[] { 
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_NONE, EditStatus.IMG_IDX_STT_NONE), 
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_EDIT, EditStatus.IMG_IDX_STT_EDIT),
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_DELETE, EditStatus.IMG_IDX_STT_DELETE),
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_NEW, EditStatus.IMG_IDX_STT_NEW)
			});
			//
			reposCheckEditObjActive.ValueChecked = Flag.Active;
			reposCheckEditObjActive.ValueUnchecked = Flag.Inactive;
			//
			reposCheckEdit.ValueChecked = Flag.Active;
			reposCheckEdit.ValueUnchecked = Flag.Inactive;
		}

		/// <summary>
		/// 
		/// </summary>
		private void LoadGroup()
		{
			try
			{
				GroupService grpSv = new GroupService();
				_grpCollection = grpSv.GetGroup();
			}
			catch (Exception ex)
			{
				Util.ShowExceptionBox(ex);
				return;
			}
			_htblUsrBelong.Clear();
			_htblFunction.Clear();
			DataTable dtblGrp = _grpCollection.DataTableGroup;
			dtblGrp.Columns.AddRange(new DataColumn[] {
				new DataColumn(TblCommon.Index,typeof(int)),
				new DataColumn(FIELD_EDIT_STATUS,typeof(string))
			});
			int count = 0;
			foreach (DataRow dtRow in dtblGrp.Rows)
			{
				count++;
				dtRow[TblCommon.Index] = count;
				dtRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_NONE;
			}
			//
			gridGroup.DataSource = dtblGrp;
		}

		private void btnReload_Click(object sender, EventArgs e)
		{
			this.LoadGroup();
		}

		private void btnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void gviewGroup_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
		{
			int rowHdl = e.FocusedRowHandle;
			gridUserBelong.DataSource = null;
			if (rowHdl < 0)
			{
				this.SetGridDbEditableStatus(true, "");
				return;
			}
			if (_grpCollection == null)
				return;
			string grpCode = Convert.ToString(gviewGroup.GetRowCellValue(rowHdl, TblGroup.Group_Code));
			//////////////////////////////////////////////////////////////////////////
			object objUbl = _htblUsrBelong[grpCode];
			DataTable dtblUserBelong = null;
			if (objUbl != null)
			{
				dtblUserBelong = (DataTable)objUbl;
			}
			else
			{
				Group grp = _grpCollection.FindGroup(grpCode);
				if (grp == null)
					return;
				dtblUserBelong = grp.ListUserBelongTo.DataTableUser;
				dtblUserBelong.Columns.AddRange(new DataColumn[] {
					new DataColumn(TblCommon.Index,typeof(int)),
				});
				int count = 0;
				foreach (DataRow dtRow in dtblUserBelong.Rows)
				{
					count++;
					dtRow[TblCommon.Index] = count;
				}
				//
				_htblUsrBelong.Add(grpCode, dtblUserBelong);
			}
			gridUserBelong.DataSource = dtblUserBelong;
			//////////////////////////////////////////////////////////////////////////
			object objFbl = _htblFunction[grpCode];
			DataTable dtbFunctionBl = null;
			if (objFbl != null)
			{
				dtbFunctionBl = (DataTable)objFbl;
			}
			else
			{
				Group grp = _grpCollection.FindGroup(grpCode);
				if (grp == null)
					return;
				dtbFunctionBl = grp.ListFunction.DataTableFunction;
				dtbFunctionBl.Columns.AddRange(new DataColumn[] {
					new DataColumn(TblCommon.Index,typeof(int)),
				});
				int count = 0;
				foreach (DataRow dtRow in dtbFunctionBl.Rows)
				{
					count++;
					dtRow[TblCommon.Index] = count;
				}
				//
				_htblFunction.Add(grpCode, dtbFunctionBl);
			}
			gridObjBelong.DataSource = dtbFunctionBl;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="bAllowEdit"></param>
		private void SetGridDbEditableStatus(bool bAllowEdit,string editStatus)
		{
			gviewGroup.Columns[TblGroup.Group_Name].OptionsColumn.AllowEdit = bAllowEdit;
			if (editStatus.Equals("") || editStatus.Equals(EditStatus.ITEM_VALUE_STT_NEW))
				gviewGroup.Columns[TblGroup.Group_Code].OptionsColumn.AllowEdit = bAllowEdit;
		}

		private void btnEdit_Click(object sender, EventArgs e)
		{
			int rowHandle = gviewGroup.FocusedRowHandle;
			if (rowHandle >= 0)
			{
				string editStatus = Convert.ToString(gviewGroup.GetRowCellValue(rowHandle,FIELD_EDIT_STATUS));
				this.SetGridDbEditableStatus(true, editStatus);
				gviewGroup.Focus();
				gviewGroup.ShowEditor();
			}
		}

		private void gviewGroup_BeforeLeaveRow(object sender, DevExpress.XtraGrid.Views.Base.RowAllowEventArgs e)
		{
			this.SetGridDbEditableStatus(false,"");
		}

		private void gviewGroup_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
		{
			int rowHandle = e.RowHandle;
			if (rowHandle < 0)
				return;
			DataRow dataRow = gviewGroup.GetDataRow(e.RowHandle);
			string editStatus = Convert.ToString(dataRow[FIELD_EDIT_STATUS]);
			if (editStatus.Equals(EditStatus.ITEM_VALUE_STT_NEW))
				return;
			string editCol = e.Column.FieldName;
			if (editCol.Equals(TblGroup.Group_Name))
				dataRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_EDIT;
		}

		private void gviewGroup_ValidatingEditor(object sender, BaseContainerValidateEditorEventArgs e)
		{
			string strFieldName = gviewGroup.FocusedColumn.FieldName;
			string strValue = Convert.ToString(e.Value).Trim();
			if (Util.IsStringEmpty(strValue))
			{
				e.ErrorText = MSG_WARNING_EMPTY_VALUE;
				e.Valid = false;
				return;
			}
			if (strFieldName.Equals(TblGroup.Group_Code))
			{
				DataTable dtblGrp = (DataTable)gridGroup.DataSource;
				int num = dtblGrp.Select(String.Format("{0}='{1}'", TblGroup.Group_Code, strValue.Trim())).Length;
				if (num > 0)
				{
					e.ErrorText = MSG_WARNING_DUPLICATE_GRP_CODE;
					e.Valid = false;
				}
			}
		
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			List<String> lstDelGrpCode = new List<String>();
			foreach (int rowHandle in gviewGroup.GetSelectedRows())
			{
				DataRow dtRow = gviewGroup.GetDataRow(rowHandle);
				string editStatus = Convert.ToString(dtRow[FIELD_EDIT_STATUS]);
				if (editStatus.Equals(EditStatus.ITEM_VALUE_STT_NEW))
					lstDelGrpCode.Add(Convert.ToString(gviewGroup.GetRowCellValue(rowHandle, TblGroup.Group_Code)));
				else
					dtRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_DELETE;
			}
			//
			foreach (string grpCode in lstDelGrpCode)
			{
				for (int i = 0; i < gviewGroup.RowCount; i++)
				{
					string curGrpCode = Convert.ToString(gviewGroup.GetRowCellValue(i,TblGroup.Group_Code));
					if (grpCode.Equals(curGrpCode)){
						gviewGroup.DeleteRow(i);
						break;
					}
				}
			}
		}

		private void gviewGroup_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
		{
			DataRow dtRow = gviewGroup.GetDataRow(e.RowHandle);
			dtRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_NEW;
			dtRow[TblCommon.Index] = gviewGroup.RowCount + 1; ;
		}

		private void gviewGroup_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
		{
			DataRow dtRow = gviewGroup.GetDataRow(e.RowHandle);
			string grpCode = Convert.ToString(dtRow[TblGroup.Group_Code]);
			string grpName = Convert.ToString(dtRow[TblGroup.Group_Name]);
			if (Util.IsStringEmpty(grpCode))
			{
				gviewGroup.SetColumnError(gridColGrpCode, ErrorMessage.MSG_WARNING_EMPTY_VALUE);
				e.Valid = false;
			}
			else if (Util.IsStringEmpty(grpName))
			{
				gviewGroup.SetColumnError(gridColGrpName, ErrorMessage.MSG_WARNING_EMPTY_VALUE);
				e.Valid = false;
			}
		}

		private void gviewGroup_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
		{
			e.ExceptionMode = ExceptionMode.NoAction;
		}

		private void btnApply_Click(object sender, EventArgs e)
		{
			DataSet dsGroup = new DataSet();
			DataTable dtblGrp = (DataTable)gridGroup.DataSource;
			dtblGrp.AcceptChanges();

            List<string> lstGroupCodeListForDelete = new List<string>();
			foreach (DataRow dtRow in dtblGrp.Rows){
				string editStatus = Convert.ToString(dtRow[FIELD_EDIT_STATUS]);
				switch (editStatus){
					case EditStatus.ITEM_VALUE_STT_EDIT:
						dtRow.SetModified();
						break;
					case EditStatus.ITEM_VALUE_STT_NEW:
						dtRow.SetAdded();
						break;
					case EditStatus.ITEM_VALUE_STT_DELETE:
                        lstGroupCodeListForDelete.Add(dtRow["GroupCode"].ToString());
						dtRow.Delete();
						break;
				}
			}
			dtblGrp.TableName = DbTable.Tbl_Group;
			dsGroup.Tables.Add(dtblGrp);
			try
			{
				GroupService grpSv = new GroupService();
                grpSv.SaveGroup(lstGroupCodeListForDelete, dsGroup);
			}
			catch (Exception ex)
			{
				Util.ShowExceptionBox(ex);
			}
			//
			this.LoadGroup();
		}
	}
}
